package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.WXApp;
import cn.hd01.service.WXAppService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/wxapp")
@Auth
public class WXAppController {
	@Autowired
	private WXAppService wxappService;

	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m) {
		return "wxapp";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<WXApp> find(WXApp u, @PageableDefault Pageable pageable) {
		return wxappService.findAll(u, pageable);
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		wxappService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(WXApp app) {
		if (app.getId() == null && (wxappService.findByDomain(app.getDomain()) != null)) {
			throw new WebException(HttpStatus.BAD_REQUEST, "微信Domain已经存在");
		}

		wxappService.save(app);
	}

}
